package com.greatmay.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.greatmay.service.GenericManager;
import com.greatmay.dao.SearchException;
import com.greatmay.model.Category;
import com.greatmay.webapp.action.BaseAction;

import java.util.List;

public class CategoryAction extends BaseAction implements Preparable {
    private GenericManager<Category, Long> categoryManager;
    private List categories;
    private Category category;
    private Long id;
    private String query;

    public void setCategoryManager(GenericManager<Category, Long> categoryManager) {
        this.categoryManager = categoryManager;
    }

    public List getCategories() {
        return categories;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String categoryId = getRequest().getParameter("category.id");
            if (categoryId != null && !categoryId.equals("")) {
                category = categoryManager.get(new Long(categoryId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        try {
            categories = categoryManager.search(query, Category.class);
        } catch (Exception se) {
            addActionError(se.getMessage());
            categories = categoryManager.getAll();
        }
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }

    public String delete() {
        categoryManager.remove(category.getId());
        saveMessage(getText("category.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            category = categoryManager.get(id);
        } else {
            category = new Category();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (category.getId() == null);

        categoryManager.save(category);

        String key = (isNew) ? "category.added" : "category.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}